package com.common.ajax.server;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.BeansException;

import com.caits.lbs.framework.Constants;
import com.caits.lbs.framework.log.CommonLogFactory;
import com.caits.lbs.framework.utils.SpringUtils;
import com.caits.lbs.framework.utils.Dom4jXmlUtil;

/**
 * <p>
 * RequestParser
 * </p>
 * <p>
 * 用途：本地处理器类，查询本地配置的IRequest实现类进行处理
 * </p>
 * 
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.1 2011-5-12
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2011-5-12 下午03:11:36</td>
 *          </tr>
 *          <tr>
 *          <td>0.0.1</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2011-5-12 下午03:11:36</td>
 *          <td>0.0.2</td>
 *          <td>修改类</td>
 *          <td>xxx</td>
 *          <td>x年x月x日</td>
 *          </tr>
 *          </table>
 */
public class RequestLocalParser implements IRequest{
	
	/** 日志记录器 */
	private Logger log = CommonLogFactory.getLog();
	
	/** 全局会话缓存 */
	protected static Map<String, SessionMap> globalMap = new ConcurrentHashMap<String, SessionMap>();

	/** 系统常量类 */
	protected Constants constant;
	/**
	 * FIXME 
	 * @throws ServletException
	 */
	public void init() {

		log.info("处理器运行在本地处理模式，Parser:" +getClass().getCanonicalName());

	}

	/** 本地处理xml方式
	 * (non-Javadoc)
	 * @see com.common.ajax.server.IRequest#request(org.jdom.Document, com.common.ajax.server.SessionMap)
	 */
	public Document request(Document doc, SessionMap session)
			throws SecurityException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException, SQLException,
			RuntimeException {
		String errorMsg = ERROR_SUCCEED_DESC;
		int result = ERROR_SUCCEED;
		Element e = doc.getRootElement();
		String className = e.attributeValue(XML_SERVER);
	
		IRequest iRequest = null;
		try {
			iRequest = (IRequest) SpringUtils.getBean(className);
		} catch (BeansException ex) {
			errorMsg = ERROR_CLASS_NOT_FOUND_DESC;
			result = ERROR_CLASS_NOT_FOUND;
			log.error(errorMsg+ex.getLocalizedMessage(), ex);
			return RequestParser.createError(className, result, errorMsg);
		}
		Document responseDoc = null;
		try {
			responseDoc = iRequest.request(doc, session);
		} catch (SQLException e1) {
			errorMsg = ERROR_SQL_DESC;
			result = ERROR_SQL_ACCESS;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		} catch (SecurityException e1) {
			errorMsg = ERROR_SECURITY_DESC;
			result = ERROR_SECURITY_ACCESS;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		} catch (RuntimeException e1) {
			errorMsg = ERROR_RUNTIME_DESC;
			result = ERROR_RUNTIME_ACCESS;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		} catch (NoSuchMethodException e1) {
			errorMsg = ERROR_METHOD_NOT_FOUND_DESC;
			result = ERROR_METHOD_NOT_FOUND;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		} catch (IllegalAccessException e1) {
			errorMsg = ERROR_ILLEGAL_ACCESS_DESC;
			result = ERROR_ILLEGAL_ACCESS;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		} catch (InvocationTargetException e1) {
			errorMsg = ERROR_INVOCATIONTARGET_DESC;
			result = ERROR_INVOCATIONTARGET_ACCESS;
			log.error(errorMsg+e1.getLocalizedMessage(), e1);
			return RequestParser.createError(className, result, errorMsg);
		}
	
		return responseDoc;
	}

	@Override
	public String request(String xmlStr, SessionMap session)
			throws SecurityException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException, SQLException,
			RuntimeException {
		String errorMsg = ERROR_SUCCEED_DESC;
		int result = ERROR_SUCCEED;
		Document doc = Dom4jXmlUtil.StringTodocument(xmlStr);
		Document responDoc = null;
		Element e = doc.getRootElement();
		String className = e.attributeValue(XML_SERVER);
		try {
			responDoc = request(doc,session);
			return responDoc.asXML();
		} catch (BeansException ex) {
			errorMsg = ERROR_CLASS_NOT_FOUND_DESC;
			result = ERROR_CLASS_NOT_FOUND;
			log.error(errorMsg+ex.getLocalizedMessage(),ex);
			return Dom4jXmlUtil.documentToString(RequestParser.createError(className, result, ERROR_CLASS_NOT_FOUND_DESC));
		}
		
	}

	/**
	 * 构建会话对象
	 * 
	 * @param cookie
	 *            - cookie的值
	 * @throws Exception
	 */
	public static  SessionMap getSession(HttpServletRequest request){
		HttpSession session = request.getSession(true);
		SessionMap ssMap = null;
		if(globalMap.containsKey(session.getId())){
			ssMap = globalMap.get(session.getId());
		}else{
			ssMap = new SessionMap(session);
			globalMap.put(session.getId(), ssMap);
		}
		
		return ssMap;
	}

	/**
	 * 获取变量constant的值
	 * @return the constant 数据类型 : Constants
	 */
	public Constants getConstant() {
		return constant;
	}

	/**
	 * 设置变量 constant 的值，数据类型：Constants
	 * @param constant the constant to set
	 */
	public void setConstant(Constants constant) {
		this.constant = constant;
	}
	
	
}
